package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.TradeSkuOrderBean;
import com.atguigu.gmall.realtime.commont.Constant;
import com.atguigu.gmall.realtime.function.DimMapFunction;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/5/4 09:33
 */
public class Dws_09_DwsTradeSkuOrderWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_09_DwsTradeSkuOrderWindow().init(
            40009,
            2,
            "Dws_09_DwsTradeSkuOrderWindow",
            Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 解析到pojo 中
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStream = parseToPojo(stream);
        // 2. 按照订单详情 id 去重
        SingleOutputStreamOperator<TradeSkuOrderBean> distinctedBeanStream = distinctByOrderDetailId(beanStream);
        // 3. 开窗聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> streamWithoutDims = windowAndAgg(distinctedBeanStream);
        // 4. 补充维度
        SingleOutputStreamOperator<TradeSkuOrderBean> streamWitDims = joinDims(streamWithoutDims);
        streamWitDims.print();
    
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> joinDims(
        SingleOutputStreamOperator<TradeSkuOrderBean> stream) {
        /*
        dim_sku_info:  spu_Id tm_id c3_id  sku_name
        dim_spu_info:  spu_name
        dim_base_trademark: tm_name
        dim_base_category3: name c2_id
        dim_base_category2: name c1_id
        dim_base_category1: name
         */
        SingleOutputStreamOperator<TradeSkuOrderBean> skuInfoStream = stream
            .map(new DimMapFunction<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_sku_info";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getSkuId();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                      JSONObject dim) {
                    bean.setSkuName(dim.getString("SKU_NAME"));
                    bean.setSpuId(dim.getString("SPU_ID"));
                    bean.setTrademarkId(dim.getString("TM_ID"));
                    bean.setCategory3Id(dim.getString("CATEGORY3_ID"));
                }
            });
        
        SingleOutputStreamOperator<TradeSkuOrderBean> spuInfoStream = skuInfoStream
            .map(new DimMapFunction<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_spu_info";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getSpuId();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                      JSONObject dim) {
                    bean.setSpuName(dim.getString("SPU_NAME"));
                }
            });
        
        SingleOutputStreamOperator<TradeSkuOrderBean> tmStream = spuInfoStream
            .map(new DimMapFunction<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_trademark";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getTrademarkId();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                      JSONObject dim) {
                    bean.setTrademarkName(dim.getString("TM_NAME"));
                }
            });
        
        SingleOutputStreamOperator<TradeSkuOrderBean> c3Stream = tmStream
            .map(new DimMapFunction<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category3";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getCategory3Id();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                      JSONObject dim) {
                    bean.setCategory3Name(dim.getString("NAME"));
                    bean.setCategory2Id(dim.getString("CATEGORY2_ID"));
                }
            });
        
        SingleOutputStreamOperator<TradeSkuOrderBean> c2Stream = c3Stream
            .map(new DimMapFunction<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category2";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getCategory2Id();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                      JSONObject dim) {
                    bean.setCategory2Name(dim.getString("NAME"));
                    bean.setCategory1Id(dim.getString("CATEGORY1_ID"));
                }
            });
        
        return c2Stream
            .map(new DimMapFunction<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category1";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getCategory1Id();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                      JSONObject dim) {
                    bean.setCategory1Name(dim.getString("NAME"));
                }
            });
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> windowAndAgg(
        SingleOutputStreamOperator<TradeSkuOrderBean> stream) {
        return stream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeSkuOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            
            )
            .keyBy(TradeSkuOrderBean::getSkuId)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeSkuOrderBean>() {
                    @Override
                    public TradeSkuOrderBean reduce(TradeSkuOrderBean value1,
                                                    TradeSkuOrderBean value2) throws Exception {
                        value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                        value1.setOriginalAmount(value1.getOriginalAmount().add(value2.getOriginalAmount()));
                        value1.setActivityAmount(value1.getActivityAmount().add(value2.getActivityAmount()));
                        value1.setCouponAmount(value1.getCouponAmount().add(value2.getCouponAmount()));
                        return value1;
                    }
                },
                new ProcessWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
                    @Override
                    public void process(String skuId,
                                        Context ctx,
                                        Iterable<TradeSkuOrderBean> elements,
                                        Collector<TradeSkuOrderBean> out) throws Exception {
                        TradeSkuOrderBean bean = elements.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                        bean.setTs(System.currentTimeMillis());  //
                        out.collect(bean);
                    }
                }
            );
        
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> distinctByOrderDetailId(
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStream) {
        return beanStream
            .keyBy(TradeSkuOrderBean::getOrderDetailId)
            .process(new KeyedProcessFunction<String, TradeSkuOrderBean, TradeSkuOrderBean>() {
                
                private ValueState<TradeSkuOrderBean> lastBeanState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastBeanState = getRuntimeContext().getState(new ValueStateDescriptor<TradeSkuOrderBean>("lastBean", TradeSkuOrderBean.class));
                }
                
                @Override
                public void processElement(TradeSkuOrderBean currentBean,
                                           Context ctx,
                                           Collector<TradeSkuOrderBean> out) throws Exception {
                    TradeSkuOrderBean lastBean = lastBeanState.value();
                    // 当第一条来了,直接输出
                    if (lastBean == null) {
                        out.collect(currentBean);
                    } else {
                        // 不是第一条, 应该用当前数据 - 上一条的数据
                        // 把减完后的数据存入到 lastBean, 然后输出
                        lastBean.setOriginalAmount(currentBean.getOriginalAmount().subtract(lastBean.getOriginalAmount()));
                        lastBean.setActivityAmount(currentBean.getActivityAmount().subtract(lastBean.getActivityAmount()));
                        lastBean.setCouponAmount(currentBean.getCouponAmount().subtract(lastBean.getCouponAmount()));
                        lastBean.setOrderAmount(currentBean.getOrderAmount().subtract(lastBean.getOrderAmount()));
                        out.collect(lastBean);
                    }
                    
                    // 当数据总是会放入到状态, 供下一条使用
                    lastBeanState.update(currentBean);
                }
            });
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
            .map(new MapFunction<String, TradeSkuOrderBean>() {
                @Override
                public TradeSkuOrderBean map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    return TradeSkuOrderBean.builder()
                        .skuId(obj.getString("sku_id"))
                        .originalAmount(obj.getBigDecimal("split_original_amount"))
                        .activityAmount(obj.getBigDecimal("split_activity_amount") == null ? new BigDecimal("0.0") : obj.getBigDecimal("split_activity_amount"))
                        .couponAmount(obj.getBigDecimal("split_coupon_amount") == null ? new BigDecimal("0.0") : obj.getBigDecimal("split_coupon_amount"))
                        .orderAmount(obj.getBigDecimal("split_total_amount"))
                        .ts(obj.getLong("ts") * 1000)
                        .orderDetailId(obj.getString("id"))
                        .build();
                }
            });
    }
}
/*
hdfs-site.xml
<property>
  <name>dfs.client.use.datanode.hostname</name>
  <value>true</value>
</property>
<property>
  <name>dfs.datanode.use.datanode.hostname</name>
  <value>true</value>
</property>


交易域SKU粒度下单各窗口

sku 维度
	统计原始金额、活动减免金额、优惠券减免金额和订单金额

1. 读取 dwd 层的数据: 下单明细表

2. 把数据解析成 pojo 类型

3. 按照详情id 去重
	下单明细表中有 left join

	详情id    sku_id      金额1(左表)  金额2(右表)   金额3(右表)   数据的生成时间
	  1        1            100        null			null       01
	  null
	  1        1            100        20			null       02
	  1        1            100        20			40         03
 
	  -----
	  极端情况下, 同一个详情会出现 3 条重复数据

	 需要按照详情id 去重

	思路 1: 开窗法
		按照详情id 分组, 使用 session 窗口, 窗口的 gap 5s, 那么这三条数据一定会进入同一个窗口

			在窗口内, 按照时间排序, 时间最大的一定是最后一条

			出结果:
				最后一条到了, 5s 之后出结果

			缺点:
				延迟大,实效性低

    思路 2: 定时器法
    	按照详情id 分组, 使用定时器

    	当第一条数据到了, 注册5s 后触发的定时器. 每来一条数据, 就比较下时间,把最大的保留(状态),
    	等到定时器触发的时候, 最多的就计算出来了

    	出结果:
    		第一条到了, 5s 之后出结果

    	相比思路 1 时效性好

    思路 3:
    	如果要用到的指标全部都在左表, 所当第一条来的时候,就可以直接输出.

    	只要第一条

    	出结果:
    		第一条到了,直接出结果

    		时效最高

    思路 4: 抵消法
	详情id    sku_id      金额1(左表)  金额2(右表)   金额3(右表)
	  1        1            100        null			null
	  1        1            100        20			null
	  1        1            100        20			40


	第一  1        1            100        0			0   直接输出
	第一反 1        1            -100       0		0   取反输出
	第二  1        1            100        20		0   直接输出
	第二反 1        1            -100       -20		0   取反输出
	第三  1        1            100        20		40  直接输出

	失效性比较高

	缺点:
		写放大问题

	避免写放大:

		第一  1        1            100              0			0       直接输出
		第二  1        1            100+(-100)=0     20+(-0)=20	0+0=0   计算后输出
		第三  1        1            100+(-100)=0     20+(-20)=0	40+(+0)=40 计算后输出



4. 按照 sku_id 分组

5. 开窗聚合

6. 补充维度
	0-5  sku_id_1    金额1  金额2 金额3
		根据 sku_id 补充这个 sku 的其他的相关维度信息: spu trademark  c3 c2 c1

    
    sql 中:
    	补充维度: 使用 lookup join

    流中:
    	自己手动实现
    	0-5  sku_id_1    金额1  金额2 金额3

    	执行 sql:
    		select * from dim_sku_info where id=sku_id
    			...

7. 最终写出到 clickhouse 中
 */